package com.lucifer.treasure.util;

import com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect;
import com.lucifer.treasure.util.SwordAuraLogger;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 御剑术共享渲染器 - 客户端和服务端统一使用服务端逻辑
 */
public class SwordAuraRenderer {

    // 🆕 击中效果剑系统
    private static final ConcurrentHashMap<String, HitEffectSword> HIT_EFFECT_SWORDS = new ConcurrentHashMap<>();
    
    // 🆕 攻击消耗和回复系统  
    private static final ConcurrentHashMap<String, Long> SWORD_RECOVERY_QUEUE = new ConcurrentHashMap<>();
    
    /**
     * 🆕 击中效果剑类
     */
    private static class HitEffectSword {
        UUID playerId;
        int swordIndex;
        Vec3d targetPos;
        LivingEntity target;
        SwordAuraEnchantmentEffect.WeaponType weaponType;
        int lifeTick;
        
        HitEffectSword(UUID playerId, int swordIndex, LivingEntity target, SwordAuraEnchantmentEffect.WeaponType weaponType) {
            this.playerId = playerId;
            this.swordIndex = swordIndex;
            this.target = target;
            this.targetPos = target.getPos();
            this.weaponType = weaponType;
            this.lifeTick = 0;
        }
        
        /**
         * 更新击中效果剑
         */
        boolean update(ServerWorld world) {
            lifeTick++;
            
            // 击中效果持续时间
            if (lifeTick > 20) { // 1秒
                return false; // 移除
            }
            
            // 简单的击中效果渲染
            world.spawnParticles(
                net.minecraft.particle.ParticleTypes.ENCHANTED_HIT,
                targetPos.x, targetPos.y + 1.0, targetPos.z,
                3, 0.3, 0.3, 0.3, 0.1
            );
            
            return true; // 继续存在
        }
    }

    /**
     * 🆕 创建击中效果剑
     */
    public static void createHitEffectSword(UUID playerId, int swordIndex, LivingEntity target, SwordAuraEnchantmentEffect.WeaponType weaponType) {
        String hitKey = playerId.toString() + "_hit_" + swordIndex;
        HIT_EFFECT_SWORDS.put(hitKey, new HitEffectSword(playerId, swordIndex, target, weaponType));
    }
    
    /**
     * 🆕 更新击中效果剑
     */
    public static void updateHitEffectSwords(ServerWorld world, UUID playerId) {
        Iterator<ConcurrentHashMap.Entry<String, HitEffectSword>> iterator = HIT_EFFECT_SWORDS.entrySet().iterator();
        
        while (iterator.hasNext()) {
            ConcurrentHashMap.Entry<String, HitEffectSword> entry = iterator.next();
            HitEffectSword sword = entry.getValue();
            
            if (sword.playerId.equals(playerId)) {
                if (!sword.update(world)) {
                    iterator.remove(); // 移除已完成的击中效果
                }
            }
        }
    }
    
    /**
     * 🎯 统一渲染方法 - 服务端逻辑
     */
    public static void renderSwordAura(PlayerEntity player, World world, int auraLevel) {
        UUID playerId = player.getUuid();
        
        // 🎯 只在服务端处理悬浮剑逻辑
        if (world instanceof ServerWorld serverWorld) {
            // 服务端：直接调用服务端逻辑
            SwordAuraEnchantmentEffect.maintainFloatingSwordsSmartly(serverWorld, player, auraLevel, world.getTime());
        } else {
            // 客户端：这里不处理，让客户端代码自己处理
            // 只做状态检查，不进行独立渲染
            if (!SwordAuraEnchantmentEffect.isAuraEnabled(playerId)) {
                // 御剑术关闭，客户端清理本地数据
                HIT_EFFECT_SWORDS.entrySet().removeIf(entry -> 
                    entry.getKey().startsWith(playerId.toString() + "_hit_"));
                SWORD_RECOVERY_QUEUE.entrySet().removeIf(entry -> 
                    entry.getKey().startsWith(playerId.toString() + "_recover_"));
                return;
            }
            
            // 🧪 调试日志
            if (world.getTime() % 100 == 0) { // 每100tick输出一次
                System.out.println("🧪 [客户端渲染] SwordAuraRenderer.renderSwordAura 被调用 - 玩家:" + 
                                 player.getName().getString() + " 等级:" + auraLevel);
            }
        }
    }

    /**
     * 🆕 设置剑视觉恢复状态
     */
    public static void setSwordVisualRecovery(UUID playerId, int swordIndex, long endTime) {
        String recoveryKey = playerId.toString() + "_recover_" + swordIndex;
        SWORD_RECOVERY_QUEUE.put(recoveryKey, endTime);
    }

    /**
     * 🆕 安排悬浮剑恢复
     */
    public static void scheduleFloatingSwordRecovery(UUID playerId, List<Integer> swordIndices, long recoverTime) {
        for (int swordIndex : swordIndices) {
            setSwordVisualRecovery(playerId, swordIndex, recoverTime);
        }
    }

    /**
     * 🆕 获取可见剑数量
     */
    public static int getVisibleSwordCount(UUID playerId) {
        // 使用服务端的方法
        return SwordAuraEnchantmentEffect.getVisibleFloatingSwordCount(playerId);
    }

    /**
     * 🆕 获取击中效果剑数量
     */
    public static int getHitEffectSwordCount(UUID playerId) {
        return (int) HIT_EFFECT_SWORDS.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(playerId.toString() + "_hit_"))
            .count();
    }

    /**
     * 🆕 获取恢复中剑数量
     */
    public static int getRecoveringSwordCount(UUID playerId) {
        return (int) SWORD_RECOVERY_QUEUE.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(playerId.toString() + "_recover_"))
            .count();
    }

    /**
     * 🆕 获取玩家移动速度（占位方法）
     */
    public static double getPlayerMoveSpeed(UUID playerId) {
        return 0.0; // 占位实现
    }

    /**
     * 🆕 获取动态更新间隔（占位方法）
     */
    public static int getDynamicUpdateInterval(UUID playerId) {
        return 2; // 占位实现，默认2tick间隔
    }

    // 🆕 客户端御剑术等级缓存（简化版）
    private static final ConcurrentHashMap<UUID, Integer> CLIENT_AURA_LEVELS = new ConcurrentHashMap<>();

    /**
     * 🆕 获取玩家御剑术等级
     */
    public static int getPlayerSwordAuraLevel(UUID playerId) {
        return CLIENT_AURA_LEVELS.getOrDefault(playerId, 0);
    }

    /**
     * 🆕 获取御剑术等级（别名方法）
     */
    public static int getAuraLevel(UUID playerId) {
        // 🎯 只使用缓存数据，避免在服务端引用客户端类
        return CLIENT_AURA_LEVELS.getOrDefault(playerId, 0);
    }

    /**
     * 🆕 设置客户端御剑术等级
     */
    public static void setClientAuraLevel(UUID playerId, int auraLevel) {
        CLIENT_AURA_LEVELS.put(playerId, auraLevel);
    }

    /**
     * 🆕 清理玩家数据
     */
    public static void cleanupPlayerData(UUID playerId) {
        HIT_EFFECT_SWORDS.entrySet().removeIf(entry -> 
            entry.getKey().startsWith(playerId.toString() + "_hit_"));
        SWORD_RECOVERY_QUEUE.entrySet().removeIf(entry -> 
            entry.getKey().startsWith(playerId.toString() + "_recover_"));
        CLIENT_AURA_LEVELS.remove(playerId);
    }

    /**
     * 🆕 清理玩家数据（别名方法）
     */
    public static void clearPlayerData(UUID playerId) {
        cleanupPlayerData(playerId);
    }
} 